package com.kugoweb.shthon2011s.tlwatch.settings;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.kugoweb.shthon2011s.tlwatch.R;
import com.kugoweb.shthon2011s.tlwatch.commons.SettingsData;
import com.kugoweb.shthon2011s.tlwatch.commons.TweetUtils;
import com.kugoweb.shthon2011s.tlwatch.service.WatchService;
import com.kugoweb.shthon2011s.tlwatch.settings.OAuthTask.OAuthTaskListener;
import com.kugoweb.shthon2011s.tlwatch.settings.SaveTokensTask.SaveTokensTaskListener;

public class SettingsActivity extends Activity implements OnClickListener,
		OAuthTaskListener, SaveTokensTaskListener {

	private Button mAccountButton;
	private SettingsData mSettingsData;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mAccountButton = (Button) findViewById(R.id.btn_account);
		mAccountButton.setOnClickListener(this);

		mSettingsData = new SettingsData(getApplicationContext());

		// Service起動
		final Intent service = new Intent(getApplicationContext(),
				WatchService.class);
		startService(service);

	}

	@Override
	public void onClick(final View view) {
		if (view == mAccountButton) {
			new OAuthTask(this, this).execute();
			// TODO Call TwitterTask
		}
	}

	@Override
	public void onBrowserCalled() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onFailure(final int errorCode) {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onNewIntent(android.content.Intent)
	 */
	@Override
	protected void onNewIntent(final Intent intent) {
		super.onNewIntent(intent);
		final Uri uri = intent.getData();
		if (uri != null && uri.toString().startsWith(TweetUtils.CALLBACK_URL)) {
			try {
				final String verifier = uri.getQueryParameter("oauth_verifier");
				// 保存する
				new SaveTokensTask(mSettingsData, verifier, this).execute();
				// Service起動
				final Intent service = new Intent(getApplicationContext(),
						WatchService.class);
				startService(service);
			} catch (final Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onSaved(final boolean deleted) {
		// TODO Auto-generated method stub

	}

}